package com.example.demo.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.demo.R;
import com.example.demo.entity.ChatContact;

import java.util.List;

public class ChatContactAdapter extends RecyclerView.Adapter<ChatContactAdapter.MyViewHolder> {
    private Context context;
    private List<ChatContact> contacts;
    private ChatOnClickListener chatOnClickListener;

    public ChatContactAdapter(Context context) {
        this.context = context;
    }


    public void setData(List<ChatContact> contacts){
        this.contacts = contacts;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_chat_contact, parent, false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        ChatContact contact = contacts.get(position);
        holder.tvName.setText(contact.getName());
        holder.imageView.setImageResource(contact.getImg());


        holder.itemChat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (chatOnClickListener != null)
                {
                    chatOnClickListener.onChatClick(contact, position);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return contacts == null ?  0 : contacts.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        TextView tvName;

        View itemChat;

        public MyViewHolder(@NonNull View itemView)
        {
            super(itemView);
            tvName = itemView.findViewById(R.id.tvName);
            imageView = itemView.findViewById(R.id.img_view);
            itemChat = itemView.findViewById(R.id.item_chat);
        }

    }

    public void setChatOnClickListener(ChatOnClickListener onClickListener)
    {
        this.chatOnClickListener = onClickListener;
    }

    // 用接口方式实现
    public interface ChatOnClickListener
    {
        void onChatClick(ChatContact contact, int position);
    }
}
